<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户管理</span>
        <div style="float: right">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAdd"
          >
            添加用户
          </el-button>
        </div>
      </div>
      <el-form :inline="true" :model="queryParams" size="small">
        <el-form-item label="用户名">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-input
            v-model="queryParams.department"
            placeholder="请输入部门"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleQuery"
          >
            搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="box-card" style="margin-top: 10px">
      <el-table
        v-loading="loading"
        :data="userList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" align="center" />
        <el-table-column
          prop="username"
          label="用户名"
          align="center"
          width="120"
        />
        <el-table-column
          prop="name"
          label="姓名"
          align="center"
          width="120"
        />
        <el-table-column
          prop="email"
          label="邮箱"
          align="center"
          width="180"
        />
        <el-table-column
          prop="phone"
          label="手机号"
          align="center"
          width="120"
        />
        <el-table-column
          prop="department"
          label="部门"
          align="center"
          width="120"
        />
        <el-table-column
          prop="position"
          label="职位"
          align="center"
          width="120"
        />
        <el-table-column
          prop="last_login_time"
          label="最后登录时间"
          align="center"
          width="180"
        />
        <el-table-column
          prop="roles"
          label="角色" 
          align="center"
          width="150"
        >
          <template #default="{ row }">
            <el-tag
              v-for="role in row.roles"
              :key="role.id"
              type="primary"
              size="small"
              style="margin-right: 5px; margin-bottom: 5px"
            >
              {{ role.name }}
            </el-tag>
            <span v-if="!row.roles || row.roles.length === 0">
              -
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          align="center"
          width="100"
        >
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="200"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="text"
              icon="el-icon-key"
              @click="handleResetPwd(row)"
            >
              重置密码
            </el-button>
            <el-button
              v-if="row.username !== 'admin'"
              size="small"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改用户对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      @closed="handleDialogClosed"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            :disabled="form.id !== undefined"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="密码" prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="form.department" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="form.position" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="角色" prop="role_ids">
          <el-select
            v-model="form.role_ids"
            multiple
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      title="重置密码"
      
      v-model="pwdOpen"
      width="400px"
      append-to-body
    >
      <el-form
        ref="pwdForm"
        :model="pwdForm"
        :rules="pwdRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="pwdForm.password"
            placeholder="请输入新密码"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="pwdForm.confirmPassword"
            placeholder="请再次输入新密码"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPwdForm">确 定</el-button>
        <el-button @click="pwdCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  getUserDetail,
  addUser,
  editUser,
  deleteUser,
  resetPassword, // [!code ++]
} from '@/api/user'
import { getAllRoles } from '@/api/role'
import Pagination from '@/components/Pagination'

export default {
  name: 'User',
  components: { Pagination },
  data() {
    const validateConfirmPwd = (rule, value, callback) => {
      if (value !== this.pwdForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: '添加用户',
      // 是否显示弹出层
      open: false,
      // 是否显示密码重置弹出层
      pwdOpen: false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        username: undefined,
        name: undefined,
        department: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 重置密码表单参数
      pwdForm: {
        id: undefined,
        password: undefined,
        confirmPassword: undefined
      },
      // 状态数据字典
      statusOptions: [
        {
          value: 1,
          label: '正常'
        },
        {
          value: 0,
          label: '停用'
        }
      ],
      // 角色选项
      roleOptions: [],
      // 表单校验
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名长度必须在2到20个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度必须在6到20个字符之间', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ]
      },
      // 密码表单校验
      pwdRules: {
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度必须在6到20个字符之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: validateConfirmPwd, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getRoleOptions()
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      getUserList(this.queryParams).then(response => {
        this.userList = response.data.data || []  
        this.total = response.data.total || 0    
        this.loading = false
      })
    },
    /** 查询角色列表 */
    getRoleOptions() {
      getAllRoles().then(response => {
        this.roleOptions = response.data
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        page: 1,
        pageSize: 10,
        username: undefined,
        name: undefined,
        department: undefined,
        status: undefined
      }
      this.handleQuery()
    },
    /** 状态修改 */
    handleStatusChange(row) {
      const text = row.status === 1 ? '启用' : '停用'
      this.$confirm(`确认要${text}用户"${row.name}"吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return editUser({ id: row.id, status: row.status, name: row.name })
      }).then(() => {
        this.$message.success(`${text}成功`)
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1
      })
    },
    /** 添加按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加用户'
    },
    /** 编辑按钮操作 */
    handleEdit(row) {
      this.reset()
      getUserDetail(row.id).then(response => {
        // 确保处理空值情况
        const userData = response.data || {}
        this.form = {
          ...userData,
          // 使用可选链运算符防止undefined错误
          role_ids: (userData.roles || []).map(role => role?.id).filter(Boolean)
        }
        this.open = true
        this.title = '编辑用户'
      }).catch(error => {  // 添加错误处理
        console.error('获取用户详情失败:', error)
        this.$message.error('获取用户信息失败')
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.pwdForm = {
        id: row.id,
        password: undefined,
        confirmPassword: undefined
      }
      this.pwdOpen = true
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(`确认删除用户"${row.name}"吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deleteUser(row.id)
      }).then(() => {
        this.getList()
        this.$message.success('删除成功')
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        username: undefined,
        password: undefined,
        name: undefined,
        email: undefined,
        phone: undefined,
        department: undefined,
        position: undefined,
        status: 1,
        role_ids: []
      }
      this.resetForm('form')
    },
    /** 重置表单 */
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
    },
    /** 密码取消按钮 */
    pwdCancel() {
      this.pwdOpen = false
      this.resetForm('pwdForm')
    },
    /** 对话框关闭时的回调 */
    handleDialogClosed() {
      this.reset()
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            editUser(this.form).then(response => {
              this.$message.success('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then(response => {
              this.$message.success('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 提交密码按钮 */
    submitPwdForm() {
      this.$refs.pwdForm.validate(valid => {
        if (valid) {
          resetPassword({ id: this.pwdForm.id, password: this.pwdForm.password }).then(response => {
            this.$message.success('密码重置成功')
            this.pwdOpen = false
            this.resetForm('pwdForm')
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.el-tag {
  margin-right: 5px;
}
.box-card {
  margin-bottom: 10px;
}
</style> 